package com.school.dishi.service.impl;

import com.school.dishi.domain.Dish;
import com.school.dishi.domain.DishFlavor;
import com.school.dishi.domain.vo.DishVO;
import com.school.dishi.mapper.DishFlavorMapper;
import com.school.dishi.mapper.DishMapper;
import com.school.dishi.service.IDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements IDishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Override
    public List<DishVO> getDishesWithFlavorsByCategoryId(Long categoryId) {
        // 1. 查询该分类下所有的菜品
        List<Dish> dishes = dishMapper.selectByCategoryId(categoryId);

        // 2. 获取所有菜品ID
        List<Long> dishIds = dishes.stream()
                .map(Dish::getId)
                .collect(Collectors.toList());

        // 3. 根据菜品ID集合，批量查询对应的口味
        Map<Long, List<DishFlavor>> flavorMap = new HashMap<>();
        if (!dishIds.isEmpty()) {
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishIds(dishIds);
            for (DishFlavor flavor : flavors) {
                Long dishId = flavor.getDishId();
                if (!flavorMap.containsKey(dishId)){
                    flavorMap.put(dishId,new ArrayList<>());
                }
                List<DishFlavor> flavorList = flavorMap.get(dishId);
                flavorList.add(flavor);
            }
        }

        // 4. 组装返回对象 DishVO
        List<DishVO> dishVOs = dishes.stream().map(dish -> {
            DishVO vo = new DishVO();
            BeanUtils.copyProperties(dish, vo); // 复制属性
            vo.setFlavors(flavorMap.getOrDefault(dish.getId(), new ArrayList<>()));
            return vo;
        }).collect(Collectors.toList());

        return dishVOs;
    }
}
